<?php

namespace app\home\middleware;


use app\common\traits\AuthTrait;
use app\home\loader\Services;
use think\Exception;
use think\facade\Config;

/**
 * 认证类
 */
class Auth
{
    use AuthTrait;

    /**
     * @param          $request
     * @param \Closure $next
     * @return mixed|void
     * @throws \Exception
     */
    public function handle($request, \Closure $next)
    {
        try {
            if ($request->method() === "OPTIONS") {
                return $next($request);
            }
            $header = $request->header();
            // 提取header的APP
            $request->request_app = $this->parseHeaderApp($header);

            $no_auth = Config::get('config');

            if ($this->checkNoAuth($request, $no_auth['no_auth'] ?? [])) {
                return $next($request);
            }
            // 获取header的认证信息
            $authInfo = $this->parseHeaderAuthorization($header);
            if (empty($authInfo)) {
                api_result(API_TIMEOUT, '登录超时,请重新登录');
            }


            // 验证用户信息
            $errorMsg = '';
            $userInfo = Services::System()->verityLogin($authInfo, $errorMsg);
            if ($userInfo === false) {
                api_result(API_ERROR, $errorMsg);
            }

            // 用户信息 保存到post中
            $request->shopUser = $userInfo;
            return $next($request);
        } catch (Exception $e) {
            api_result($e);
        }
    }
}
